var Wxindex = function() {

    var defaultContent="<button type=\"button\" class=\"btn blue btn_edit_role\">修改</button><button type=\"button\" class=\"btn red btn_del_role\">删除</button>";
    var storeId = $('#store').find("option:selected").val();

    // 以下模板并没有作用，因为页面会被重新加载
    var advertisement = stringLines(function(){/*
    <div class="col-md-8 ban-site site advertisement" id="" draggable="true">
        <input name="componentId" type="hidden" value="" />
        <div class="btn-group" style="display: block;">
            <input name="frameId" value="" type="hidden">
            <span class="glyphicon glyphicon-move ui-sortable-handle"></span>
            <button type="button" class="btn btn-xs btn_del_module glyphicon glyphicon-trash"></button>
        </div>
        <h4>轮播图</h4>
        <button type="button"
                class="btn btn-success margin-top-10 margin-bottom-10 btn_add_class"
                id="advertisement_btn"><span
                class="glyphicon glyphicon-plus-sign"></span> 新增轮播广告
        </button>
        <table class="table table-ban" id="advertisement_talbe">
            <thead>
            <tr>
                <th>广告图片</th>
                <th>链接类型</th>
                <th>排序</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
*/});
    var iconArea = stringLines(function(){/*
    <div class="col-md-8 btn-nav-site site" id="">
        <input name="componentId" type="hidden" value="" />
        <div class="btn-group" style="display: block;">
            <input name="frameId" value="" type="hidden">
            <span class="glyphicon glyphicon-move ui-sortable-handle"></span>
            <button type="button" class="btn btn-xs btn_del_module glyphicon glyphicon-trash"></button>
        </div>
        <h4>按钮导航设置</h4>
        <div class="form-inline form-group  relative">
            <label class="control-label pull-left">一行显示数：</label>
            <div class="col-md-6 col-xs-7">
                <label class="radio-inline">
              <input type="radio" name="displayType" value="2" > 两个
            </label>
                <label class="radio-inline">
              <input type="radio" name="displayType" value="3"> 三个
            </label>
                <label class="radio-inline">
              <input type="radio" name="displayType" value="4"> 四个
            </label>
            </div>
        </div>
        <div class="form-inline form-group relative">
            <button type="button" class="btn glyphicon glyphicon-ok yellow iconArea_sure">确认</button>
        </div>
        <button type="button" id="iconArea_btn" class="btn btn-success margin-top-10 margin-bottom-10 btn_add_class"><span class="glyphicon glyphicon-plus-sign"></span> 新增按钮导航</button>
        <table class="table table-ban" id="">
            <thead>
                <tr>
                    <th>按钮图片</th>
                    <th>按钮名称</th>
                    <th>链接类型</th>
                    <th>排序</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
*/});
    var commodity = stringLines(function(){/*
    <div class="col-md-8 btn-pro-site site"  id="commoditylist">
        <h4>推荐内容设置</h4>
        <div class="form-group relative" style="display: none;">
            <label class="control-label pull-left">模块标题：　</label>
            <div class="col-md-6 col-xs-7 text_title form-inline">
                <input type="text" class="form-control input-medium" name="frameName" maxlength="12" value="" />
            </div>
        </div>
        <div class="form-group relative">
            <label class="control-label pull-left">显示内容：　</label>
            <div class="col-md-6 col-xs-7 contentType form-inline">
                <select name="ctype" onchange="changeType(this)" >
                    <option value="1" >商品</option>
                    <option value="2" >文章</option>
                    <option value="3" >拼团</option>
                    <option value="4" >积分兑换</option>
                </select>
            </div>
        </div>
        <div class="form-inline form-group relative">
            <label class="control-label pull-left">显示布局：　</label>
            <div class="col-md-6 col-xs-7">
                <label class="radio-inline list">
                    <input type="radio" name="displayType2" value="1" checked > 列表布局
                </label>
                <label class="radio-inline trell" >
                    <input type="radio" name="displayType2" value="2"  > 方格布局
                </label>
                <label class="radio-inline skip" >
                    <input type="radio" name="displayType2" value="3"  > 滑动布局
                </label>
            </div>
        </div>
        <div class="form-inline form-group margin-top-30 relative">
            <label class="control-label pull-left">　　　　　　</label>
            <div class="col-md-6 col-xs-7">
                <button type="button" id="updateName_btn"
                        class="btn glyphicon glyphicon-ok yellow">确认
                </button>
            </div>
        </div>
    </div>
*/});
    var pic = stringLines(function(){/*
    <div class="col-md-8 btn-pic-site site" style="display: none;">
        <div class="btn-group" style="display: block;">
            <input name="frameId" value="" type="hidden">
            <span class="glyphicon glyphicon-move ui-sortable-handle"></span>
            <button type="button" class="btn btn-xs btn_del_module glyphicon glyphicon-trash"></button>
        </div>
        <h4>自适应图片设置</h4>
        <div class="form-group margin-top-30 relative" style="display: none;">
            <label class="control-label pull-left">模块标题：　</label>
            <div class="col-md-6 col-xs-7">
                <label class="radio-inline">
                    <input type="radio" name="titleType" value="文字标题">文字标题
                </label>
                <label class="radio-inline">
                    <input type="radio" name="titleType" value="图片标题">图片标题
                </label>
            </div>
        </div>
        <div class="form-group margin-top-20 relative">
            <label class="control-label pull-left"></label>
            <div class="col-md-6 col-xs-7 text_title form-inline"
                 style="display: block;">
                <input type="text" class="form-control input-medium" id="frameName"  name="frameName" maxlength="12"/></div>
            <div class="col-md-6 col-xs-7 pic_title" style="display: none;">
                <div id="btn-uploader" class="relative pull-left">
                    <a id="pickfiles9" href="javascript:void 0;"
                       style="position: relative; z-index: 1;"><img name="img_qiniu_url" class="img_qiniu_url"></a>
                    <div id="html5_1bufvfi899og15b01rvn1r3sov4_container" class="moxie-shim moxie-shim-html5" style="position: absolute; top: 0px; left: 27px; width:140px; height: 70px; overflow: hidden; z-index: 0;">
                        <input id="html5_1bufvfi899og15b01rvn1r3sov4" type="file" style="font-size: 999px; opacity: 0; position: absolute; top: 0px; left: 0px; width:100%; height: 100%;" accept=".jpg,.jpeg,.gif,.png" tabindex="-1"></div>
                </div>
                <div class="pull-left margin-left color9">图片格式：png、jpg、gif；<br/>图片尺寸：750×120像素；<br/>图片大小：不超过500K
                </div>
            </div>
        </div>
        <div class="form-inline form-group margin-top-30 relative">
            <label class="control-label pull-left"></label>
            <div class="col-md-6 col-xs-7">
                <button type="button" id="pic_sure_btn" class="btn glyphicon glyphicon-ok yellow">确认
                </button>
            </div>
        </div>
        <button type="button" id="pic_btn" class="btn btn-success btn_add_class"><span class="glyphicon glyphicon-plus-sign"></span> 新增图片
        </button>
        <table class="table table-ban" id="pic_ban_table">
            <thead>
            <tr>
                <th> 图片</th>
                <th> 链接</th>
                <th> 排序</th>
                <th> 操作</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
*/});
    var video = stringLines(function(){/*
    <div class="col-md-8 btn-video-site site" id="">
        <h4>视频模块设置</h4>
        <div class="form-group margin-top-10 relative">
            <label class="control-label pull-left">视频标题：　</label>
            <div class="col-md-6 col-xs-8 text_title form-inline" style="display: block;">
                <input type="text" class="form-control input-medium" id="" name="frameName" value="" maxlength="12">
            </div>
        </div>
        <div class="form-group margin-top-10 relative ">
            <lable class="pull-left control-label">
                视频封面：
            </lable>
            <div class="col-md-6 col-xs-8">
                <div class="pull-left margin-left"  onclick="getAllPic(this,size='2')">
                    <a id="pickfiles6" href="javascript:void 0;"><img class="img-responsive" name="img_qiniu_url"/></a>
                </div>
                <small class="center-block pull-left margin-left">
                    图片推荐：尺寸670*357，大小不超过500k<br/>
                </small>
            </div>
        </div>
        <div class="form-group margin-top-10 relative">
            <lable class="pull-left control-label">
                <span class="required"> * </span>视频地址：
            </lable>
            <div class="col-md-6 col-xs-8 text_title form-inline" style="display: block;">
                <input type="text" class="form-control" name="videoUrl" maxlength="12"/>
            </div>
        </div>
        <div class="form-inline form-group margin-top-30 relative">
            <label class="control-label pull-left"></label>
            <div class="col-md-6 col-xs-8">
                <button type="button" id="video_sure_btn"
                        class="btn glyphicon glyphicon-ok yellow">确认
                </button>
            </div>
        </div>
    </div>
*/});
    var quan = stringLines(function() {/*
    <div class="col-md-8 btn-pro-site site"  id="commoditylist">
        <div class="btn-group" style="display: block;">
            <input name="frameId" value="{$vo.id}" type="hidden">
            <span class="glyphicon glyphicon-move ui-sortable-handle"></span><button type="button" class="btn btn-xs btn_del_module glyphicon glyphicon-trash"></button>
        </div>
        <h4>代金券样式</h4>
        <div class="form-group margin-top-30 relative">
            <span class="quan"><input type="radio" name="quan" value="1"><img src="/public__STATIC__/admin/pages/image/quan1.png" alt="" ></span>
            <span class="quan"><input type="radio" name="quan" value="2"><img src="/public__STATIC__/admin/pages/image/quan2.png" alt="" ></span>
            <span class="quan"><input type="radio" name="quan" value="3"><img src="/public__STATIC__/admin/pages/image/quan3.png" alt="" ></span>
        </div>
        <div class="form-inline form-group margin-top-30 relative">
            <label class="control-label pull-left"></label>
            <div class="col-md-6 col-xs-7">
                <button type="button" id="updateName_btn" class="btn glyphicon glyphicon-ok yellow">确认</button>
            </div>
        </div>
    </div>
*/});
    var nearbystore = stringLines(function() {/*
    <div class="col-md-8 ban-site site advertisement" id="" >
        <input name="componentId" type="hidden" value="" />
        <div class="btn-group" style="display: block;">
            <input name="frameId" value="{$vo.id}" type="hidden">
            <span class="glyphicon glyphicon-move ui-sortable-handle"></span><button type="button" class="btn btn-xs btn_del_module glyphicon glyphicon-trash"></button>
        </div>
        <h4 style="color: #000;">附近门店设置</h4>
        <div class="row">
            <div class="col-md-3">
                <select name="nearby_storeId" class="form-control">

                </select>
            </div>
            <div class="col-md-3">
                <button type="button" class="btn btn-success btn_add_class nearbystore_btn" id="nearbystore_btn"> 添加门店
                </button>
            </div>
        </div>
        <span class="help-block text-center" style="color: red"></span>
        <table class="table table-ban nearbystore_talbe" id="nearbystore_talbe{$key}">
            <thead>
            <tr>
                <th>门店图</th>
                <th>门店名称</th>
                <th>门店地址</th>
                <th>排序</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
*/});
    var dividingline = stringLines(function() {/*
    <hr />
*/});


    var _init = function() {
        // 轮播图
        handle_advertisement();
        // 按钮导航
        handle_iconArea();
        // 自适应图片
        handle_pic_ban();
        // 推荐内容
        handle_updateName();
        // 代金券
        handle_quan();
        // 视频
        handle_vedio();
        // 附近门店
        handle_nearbystore();
        // 分割线
        handle_dividingline();
    };

    // 轮播图
    var handle_advertisement = function () {
        $("#applet .advertisement_talbe").each(function(i){
            var listid = $(this).parent().attr('id');
            var index = listid.substr(4);
            var table = $('#advertisement_talbe'+index);
            var frameId = $("#"+listid).find('[name="frameId"]').val();  //模块id
            var test = $('#con_mainList'+index);
            table.dataTable({
                "processing": false,
                destroy:false,
                serverSide: false,// 关闭服务器模式
                "ajax": {
                    url:componentList_url, // 列表查询
                    data:{'frameId':frameId}
                },
                "autoWidth": false,
                "columns": [
                    {
                        "width": "20%",
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            return "<img class='img-responsive center-block' src='"+data+"' alt='' />"
                        }
                    },
                    {
                        "width": "20%",
                        "data": "linkType",
                        "render": function(data, type, row, meta) {
                            return mdTool.getLikeTpe(data);
                        }
                    },
                    {"width": "10%","data": "orderNo"},
                    {"width": "25%","data": "null","defaultContent": defaultContent}
                ],
                "language": {
                    url: '/public/static/assets/pages/Chinese.json'
                },
                "pageLength": 5,
                "order": [
                    [2, "asc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 3]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){   //将第一张图片放到相应预览位置
                    if(iDataIndex == 0) {
                        $(test).find('img').attr('src',aData['imgUrl']);
                    }
                },
                "fnInitComplete": function() {}
            });

            // 新增或保存
            table.on('click', '.btn_save_role', function(event) {
                console.log('add');
                var imgUrl = $(this).parent().parent().find('[name="img_qiniu_url"]')[0].src;
                var displayName = $("#"+listid).find('[name="displayName"]').val();
                var orderNo = $("#"+listid).find('[name="orderNo"]').val();
                var linkType = $("#"+listid).find('[name="linkType"]').val();
                var linkId = $("#"+listid).find('[name="linkId"]').val();

                var _id = $("#"+listid).find('[name="componentId"]').val();  //模块内容id
                var frameId = $("#"+listid).find('[name="frameId"]').val();  //模块id
                var msgId="list"+index+" .help-block";

                if (!mdTool.validate(imgUrl, 'require')) {
                    $("#"+listid).find('.help-block').html('请上传图片');
                    return;
                }
                if (!mdTool.validate(linkType, 'require')) {
                    $("#"+listid).find('.help-block').html('请选择链接类型');
                    return;
                }
                if(!isRequireLinkId(linkType)){
                    linkId="";
                }else if (!mdTool.validate(linkId, 'require')) {
                    $("#"+listid).find('.help-block').html('请选择弹框信息');
                    return;
                }
                if (!mdTool.validate(orderNo, 'num')) {
                    $("#"+listid).find('.help-block').html('请输入正确的排序');
                    return;
                }else {
                    imgUrl = imgUrl;
                    var param={"id":_id,"imgUrl":imgUrl,"orderNo":orderNo,"linkType":linkType,"linkId":linkId,"displayName":displayName,"frameId":frameId};
                    var _type = _id == null||_id == '' ? "put" : "post";

                    $.ajax({
                        url : component_url,
                        type : _type,
                        dataType : 'json',
                        contentType:"application/json; charset=utf-8",
                        data : JSON.stringify(param),
                    }).done(function(data) {
                        if (data.code === '1') { // 正确
                            table.DataTable().ajax.reload();
                            //table.DataTable().draw(false);
                            $("#"+listid).find('.advertisement_btn').attr("disabled",false);
                            // window.location.reload();
                            $(' .help-block').html('');
                        } else if (data.code === '2') { // 错误
                            $("#"+listid).find('.help-block').html(data.message);
                        }
                    });
                }
            });

            // 修改
            table.on('click', '.btn_edit_role', function(event) {
                $(this).attr("disabled","disabled");
                $(this).parents("tr").siblings("tr").find(".btn_edit_role").attr("disabled","disabled");
                $(this).parents(".site").find(".btn_add_class").attr("disabled","disabled");
                var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); //操作行对象
                var _id = oData_arr[0].id;
                var imgUrl = oData_arr[0].imgUrl;
                var orderNo = oData_arr[0].orderNo;
                var linkType = oData_arr[0].linkType;
                var linkId = oData_arr[0].linkId;
                var displayName = oData_arr[0].displayName;

                $(this).parent().parent().parent().parent().find("tbody:last").append(advertisementTemplate);
                $('#btn-uploader [ type="button"]').css('background',"url("+imgUrl+")");
                $('#btn-uploader [ type="button"]').css('background-size',"100%");
                $("#"+listid).find('[name="img_qiniu_url"]').attr('src',imgUrl);
                $("#"+listid).find('[name="orderNo"]').val(orderNo);
                $("#"+listid).find('[name="linkId"]').val(linkId);
                $("#"+listid).find('[name="linkType"]').val(linkType);
                $("#"+listid).find('input[name="componentId"]').val(_id);

            });

            // 删除
            table.on('click', '.btn_del_role', function(event) {
                var oData_arr = table.DataTable().rows($(this).parents("tr")).data();
                var _id = oData_arr[0].id;
                deleteComponent(_id,table);
            });
        });

        // 添加轮播图
        $('.advertisement_btn').click(function(event){
            var count = $(this).parent().find('table tbody').children('tr').length;
            if(count >= 8) {
                layer.msg('最多添加8张图片');
                return;
            }
            $(this).attr("disabled","disabled");
            $(this).parent().find('table .btn_edit_role').attr("disabled","disabled");
            $(this).parent().find('table tbody:last').append(advertisementTemplate);
            $(this).parent().find('[name="componentId"]').val("");
        });
    };

    // 按钮导航
    var handle_iconArea = function () {
        $("#applet .iconArea_talbe").each(function(i){
            var listid = $(this).parent().attr('id');
            var index = listid.substr(4);
            var iconArea_talbe = $('#iconArea_talbe'+index);
            var frameId = $("#"+listid).find('[name="frameId"]').val();  //模块id
            var test = $('#con_mainList'+index);
            iconArea_talbe.dataTable({
                "processing": false,
                serverSide: false, // 服务器模式
                "ajax": {
                    url:componentList_url, //列表查询
                    data:{'frameId':frameId}
                },
                destroy:true,
                "autoWidth": false,
                "columns": [
                    {
                        "width": "10%",
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            return "<img class='img-responsive center-block' src='"+data+"' alt='' />"
                        }
                    },
                    {"width": "20%","data": "displayName"},
                    {
                        "width": "20%",
                        "data": "linkType",
                        "render": function(data, type, row, meta) {
                            return mdTool.getLikeTpe(data);
                        }
                    },
                    {"width": "10%","data": "orderNo"},
                    {"width": "25%","data": "null","defaultContent": defaultContent}
                ],
                "language": {
                    url: '/public/static/assets/pages/Chinese.json'
                },
                "pageLength": 5,
                "order": [
                    [3, "asc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 4]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){   //将每张图片放到相应预览位置
                    if($(test).find('.col-md-12 .iconArea .icon'+iDataIndex).length > 0) {
                        $(test).find('.col-md-12 .iconArea .icon'+iDataIndex).find('img').attr('src',aData['imgUrl']);
                    } else {
                        var $displayType = $('.iconAreaList').find("input[name='displayType"+index+"']:checked").val();
                        var $class = 4;  //3列布局
                        if($displayType == 2) {
                            $class = 6;  //2列布局
                        } else if($displayType == 4) {
                            $class = 3;  //4列布局
                        }
                        var $item = ($('<div class="col-md-'+$class+' col-xs-4 margin-bottom-15 icon'+iDataIndex+'"><img class="img-responsive margin-bottom-5" style="height:42px;width:42px" src="'+
                            aData['imgUrl']+'" /><span class="center-block text-center">'+aData['displayName']+'</span></div>'));
                        $(test).find('.col-md-12 .iconArea').append($item);
                    }
                },
                "fnInitComplete": function() {}
            });

            // 新增或保存
            iconArea_talbe.on('click', '.btn_save_role', function(event) {
                var oData_arr = iconArea_talbe.DataTable().rows($(this).parents("tr")).data(); // 操作行对象

                var _id = $("#"+listid).find('[name="componentId"]').val();  //模块内容id
                var imgUrl = $(this).parent().parent().find('[name="img_qiniu_url"]')[0].src;
                var displayName = $("#"+listid).find('[name="displayName"]').val();
                var orderNo = $("#"+listid).find('[name="orderNo"]').val();
                var linkType = $("#"+listid).find('[name="linkType"]').val();
                var linkId = $("#"+listid).find('[name="linkId"]').val();

                if (!mdTool.validate(imgUrl, 'require')) {
                    $("#"+listid).find('.help-block').html('请上传图片');
                    return;
                }
                if (!mdTool.validate(displayName, 'require')) {
                    $("#"+listid).find('.help-block').html('请输入按钮名称');
                    return;
                }
                if (!mdTool.validate(linkType, 'require')) {
                    $("#"+listid).find('.help-block').html('请选择链接类型');
                    return;
                }
                if(!isRequireLinkId(linkType)){
                    linkId="";
                }else if (!mdTool.validate(linkId, 'require')) {
                    $("#"+listid).find('.help-block').html('请选择弹框信息');
                    return;
                }
                if (!mdTool.validate(orderNo, 'num')) {
                    $("#"+listid).find('.help-block').html('请输入正确的排序');
                    return;
                }else {
                    imgUrl = imgUrl;
                    var param={"id":_id,"imgUrl":imgUrl,"orderNo":orderNo,"linkType":linkType,"linkId":linkId,"displayName":displayName,"frameId":frameId};
                    var _type = _id == null||_id == '' ? "put" : "post";

                    $.ajax({
                        url : component_url,
                        type : _type,
                        dataType : 'json',
                        contentType:"application/json; charset=utf-8",
                        data : JSON.stringify(param),
                    }).done(function(data) {
                        if (data.code === '1') {
                            // 正确
                            iconArea_talbe.DataTable().ajax.reload();
                            $("#"+listid).find('.iconArea_btn').attr("disabled",false);
                            $("#"+listid).find('.help-block').html('');
                        } else if (data.code === '2') {// 错误
                            $("#"+listid).find('.help-block').html(data.message);
                        }
                    });
                }
            });

            // 修改
            iconArea_talbe.on('click', '.btn_edit_role', function(event) {
                $(this).attr("disabled","disabled");
                $(this).parents("tr").siblings("tr").find(".btn_edit_role").attr("disabled","disabled");
                $(this).parents(".site").find(".btn_add_class").attr("disabled","disabled");

                var oData_arr = iconArea_talbe.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
                var _id = oData_arr[0].id;
                var imgUrl = oData_arr[0].imgUrl;
                var orderNo = oData_arr[0].orderNo;
                var linkType = oData_arr[0].linkType;
                var displayName = oData_arr[0].displayName;
                var linkId = oData_arr[0].linkId;

                $("#"+listid).find("table tbody:last").append(iconTemplate);
                $('#btn-uploader [ type="button"]').css('background',"url("+imgUrl+")");
                $('#btn-uploader [ type="button"]').css('background-size',"100%");

                $("#"+listid).find('[name="img_qiniu_url"]').attr('src',imgUrl);
                $("#"+listid).find('[name="orderNo"]').val(orderNo);
                $("#"+listid).find('[name="linkId"]').val(linkId);
                $("#"+listid).find('[name="linkType"]').val(linkType);
                $("#"+listid).find('[name="displayName"]').val(displayName);
                $("#"+listid).find('input[name="componentId"]').val(_id);

            });

            // 删除
            iconArea_talbe.on('click', '.btn_del_role', function(event) {
                var oData_arr = iconArea_talbe.DataTable().rows($(this).parents("tr")).data();
                var _id = oData_arr[0].id;
                deleteComponent(_id,iconArea_talbe);
            });
        });

        // 添加按钮导航
        $('.iconArea_btn').click(function(event){
            var count = $(this).parent().find('table tbody').children('tr').length;
            if(count >= 12) {
                layer.msg('最多添加12个按钮');
                return;
            }
            $(this).attr("disabled","disabled");
            $(this).parent().find('table .btn_edit_role').attr("disabled","disabled");
            $(this).parent().find('table tbody:last').append(iconTemplate);
            $(this).parent().find('[name="componentId"]').val("");
        });

        // 按钮导航设置确认按钮
        $('.iconArea_sure').on('click', function(event) {
            var listid = $(this).parent().parent().attr('id');
            var index = listid.substr(4);
            var frameId = $(this).parent().parent().find('[name="frameId"]').val();
            var displayType = $(this).parent().prev().find("input[name='displayType"+index+"']:checked").val();
            var param={"id":frameId,"displayType":displayType};
            var msgId=$(this).next();
            $(this).attr('disabled',true);

            ajaxFrameReq(param,msgId);
        });
    };

    // 自适应图片
    var handle_pic_ban = function () {
        $("#applet .pic_ban_table").each(function(i){
            var listid = $(this).parent().attr('id');
            var index = listid.substr(4);
            var pic_ban_table = $('#pic_ban_table'+index);
            var frameId = $("#"+listid).find('[name="frameId"]').val();  //模块id
            var test = $('#con_mainList'+index);

            pic_ban_table.dataTable({
                "processing": false,
                serverSide: false,   // 服务器模式
                destroy:true,
                "ajax": {
                    url:componentList_url, // 列表查询
                    data:{'frameId':frameId}
                },
                "autoWidth": false,
                "columns": [
                    {
                        "width": "17%",
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            return "<img class='img-responsive center-block' src='"+data+"' alt='' />"
                        }
                    },
                    {
                        "width": "20%",
                        "data": "linkType",
                        "render": function(data, type, row, meta) {
                            return mdTool.getLikeTpe(data);
                        }
                    },
                    {"width": "25%","data": "orderNo"},
                    {"width": "25%","data": "null","defaultContent": defaultContent}
                ],
                "language": {
                    url: '/public/static/assets/pages/Chinese.json'
                },
                "pageLength": 5,
                "order": [
                    [2, "asc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 3]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){   //将每张图片放到相应预览位置
                    if($(test).find('.col-md-12 .autoimg'+iDataIndex).length > 0) {
                        $(test).find('.col-md-12 .autoimg'+iDataIndex).find('img').attr('src',aData['imgUrl']);
                    } else {
                        var $item = ($('<div class="row autoimg'+iDataIndex+'"><div><div class=" col-xs-12 margin-bottom-10"><img class="img-responsive carousel-inner" src="'+
                            aData['imgUrl']+'" /></div></div></div>'));
                        $(test).find('.col-md-12').append($item);
                    }
                },
                "fnInitComplete": function() {}
            });

            // 新增或保存
            pic_ban_table.on('click', '.btn_save_role', function(event) {
                var oData_arr = pic_ban_table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象

                var _id = $("#"+listid).find('[name="componentId"]').val();  //模块内容id
                var imgUrl = $(this).parent().parent().find('[name="img_qiniu_url"]')[0].src;
                var orderNo = $("#"+listid).find('[name="orderNo"]').val();
                var linkType = $("#"+listid).find('[name="linkType"]').val();
                var linkId = $("#"+listid).find('[name="linkId"]').val();

                var param={"id":_id,"orderNo":orderNo,"linkId":linkId,"frameId":frameId,"displayName":'自适应图片',"linkType":linkType,"imgUrl":imgUrl};

                if (!mdTool.validate(imgUrl, 'require')) {
                    $("#"+listid).find('.help-block').html('请上传图片');
                    return;
                }
                if (!mdTool.validate(linkType, 'require')) {
                    $("#"+listid).find('.help-block').html('请选择链接类型');
                    return;
                }
                if(!isRequireLinkId(linkType)) {
                    linkId="";
                }else if (!mdTool.validate(linkId, 'require')) {
                    $("#"+listid).find('.help-block').html('请选择弹框信息');
                    return;
                }
                if (!mdTool.validate(orderNo, 'num')) {
                    $("#"+listid).find('.help-block').html('请输入正确的排序');
                    return;
                }else {
                    var _type = _id == null||_id == '' ? "post" : "put";

                    $.ajax({
                        url : component_url,
                        type : _type,
                        dataType : 'json',
                        contentType:"application/json; charset=utf-8",
                        data : JSON.stringify(param),
                    }).done(function(data) {
                        if (data.code === '1') { // 正确
                            pic_ban_table.DataTable().ajax.reload();
                            //pic_ban_table.DataTable().draw(false);
                            $("#"+listid).find('.pic_btn').attr("disabled",false);
                            $("#"+listid).find('.help-block').html('');
                        } else if (data.code === '2') { // 错误
                            $("#"+listid).find('.help-block').html(data.message);
                        }
                    });
                }
            });

            // 修改
            pic_ban_table.on('click', '.btn_edit_role', function(event) {
                $(this).attr("disabled","disabled");
                $(this).parents("tr").siblings("tr").find(".btn_edit_role").attr("disabled","disabled");
                $(this).parents(".site").find(".btn_add_class").attr("disabled","disabled");

                var oData_arr = pic_ban_table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
                var _id = oData_arr[0].id;
                var imgUrl = oData_arr[0].imgUrl;
                var orderNo = oData_arr[0].orderNo;
                var linkType = oData_arr[0].linkType;
                var displayName = oData_arr[0].displayName;
                var linkId = oData_arr[0].linkId;

                $("#"+listid).find("table tbody:last").append(picTemplate);
                $("#"+listid).find('[name="img_qiniu_url"]').attr('src',imgUrl);
                $("#"+listid).find('[name="orderNo"]').val(orderNo);
                $("#"+listid).find('[name="linkId"]').val(linkId);
                $("#"+listid).find('[name="linkType"]').val(linkType);
                $("#"+listid).find('[name="displayName"]').val(displayName);
                $("#"+listid).find('input[name="componentId"]').val(_id);
            });

            // 删除
            pic_ban_table.on('click', '.btn_del_role', function(event) {
                var oData_arr = pic_ban_table.DataTable().rows($(this).parents("tr")).data();
                var _id = oData_arr[0].id;
                deleteComponent(_id,pic_ban_table);
            });
        });

        // 添加自适应图片
        $('.pic_btn').click(function(event){
            $(this).parent().find("table tbody:last").append(picTemplate);
            $(this).attr("disabled","disabled");
            $(this).parent().find("table .btn_edit_role").attr("disabled","disabled");
            $(this).parent().find('[name="componentId"]').val("");
        });

        // 自适应图片确认按钮
        $('.pic_sure_btn').on('click', function(event) {
            var frameName= $(this).parent().parent().parent().find('[name="frameName"]').val();
            var frameId = $(this).parent().parent().parent().find('[name="frameId"]').val();

            var param={"id":frameId,"name":frameName};
            var msgId=$(this).next();
            if (!mdTool.validate(frameName, 'require')) {
                $(this).next().html('请填写模块标题');
                return;
            }else {
                $(this).attr('disabled',true);

                ajaxFrameReq(param,msgId);
            }
        });
    };

    // 推荐内容
    var handle_updateName = function () {
        // 推荐内容确认按钮
        $('.updateName_btn').on('click', function(event) {
            //console.log(this);
            var listid = $(this).parent().parent().parent().attr('id');
            var index = listid.substr(4);
            var frameName= $(this).parent().parent().parent().find('[name="frameName"]').val();
            var frameId = $(this).parent().parent().parent().find('[name="frameId"]').val();
            var displayType = $(this).parent().parent().parent().find("input[name='displayType"+index+"']:checked").val();
            var type = $(this).parent().parent().parent().find("select[name='ctype'] option:selected").val();
            var orderType = $(this).parent().parent().parent().find("select[name='orderType'] option:selected").val();

            var param={"id":frameId,"name":frameName,"contentType":type,"displayType":displayType,'orderType':orderType};
            var msgId=$(this).next();
            if (!mdTool.validate(frameName, 'require')) {
                msgId.html('请填写模块标题');
                return;
            } else {
                $(this).attr('disabled',true);

                ajaxFrameReq(param,msgId);
            }
        });
    };

    // 代金券
    var handle_quan = function () {
        // 代金券样式选择确认按钮
        $('.quan_sure_btn').on('click',function(event) {
            var listid = $(this).parent().parent().parent().attr('id');
            var index = listid.substr(4);
            var frameName= $(this).parent().parent().parent().find('[name="frameName"]').val();
            var frameId = $(this).parent().parent().parent().find('[name="frameId"]').val();
            var displayType = $(this).parent().parent().parent().find("input[name='quan"+index+"']:checked").val();

            var msgId=$(this).next();
            if (!mdTool.validate(frameName, 'require')) {
                msgId.html('请填写模块标题');
                return;
            }
            var param={"id":frameId,"name":frameName,"displayType":displayType};
            $(this).attr('disabled',true);

            ajaxFrameReq(param,msgId);
        });
    };

    // 视频
    var handle_vedio = function () {
        // 视频确认按钮
        $('.video_sure_btn').on('click', function(event) {
            var listid = $(this).parent().parent().parent().attr('id');
            var index = listid.substr(4);

            var frameName= $(this).parent().parent().parent().find('[name="frameName"]').val();
            var frameId = $(this).parent().parent().parent().find('[name="frameId"]').val();
            var imgUrl= $('#pickfiles'+index+' [name="img_qiniu_url"]')[0].src;
            var videoUrl= $('#videofiles'+index+' [name="img_qiniu_url"]')[0].src;
            var msgId= $(this).next();

            if (!mdTool.validate(imgUrl, 'require')) {
                msgId.html('请选择图片标题');
                return;
            }
            if (!mdTool.validate(videoUrl, 'require')) {
                msgId.html('请上传视频');
                return;
            }
            imgUrl = imgUrl;
            var param = {"frame":{"id":frameId,"name":frameName,"displayType":"1"},
                "WxComponentConf":{"frameId":frameId,"linkType":5,"orderNo":"1","displayName":"视频","imgUrl":imgUrl,"videoUrl":videoUrl
                }};
            $(this).attr('disabled',true);

            ajaxFrameReqVideo(param,msgId);
        });
    };

    // 附近门店
    var handle_nearbystore = function () {
        $("#applet .nearbystore_talbe").each(function(i){
            var listid = $(this).parent().attr('id');
            var index = listid.substr(4);
            var nearbystore_talbe = $('#nearbystore_talbe'+index);
            var frameId = $("#"+listid).find('[name="frameId"]').val();  //模块id
            var test = $('#con_mainList'+index);

            nearbystore_talbe.dataTable({
                "processing": false,
                "ordering": false, // 禁止排序
                serverSide: false,   // 服务器模式
                destroy:true,
                "ajax": {
                    url: componentStoreList_url, // 列表查询
                    data:{'frameId':frameId}
                },
                "autoWidth": false,
                "columns": [
                    {
                        "width": "10%",
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            return "<img class='img-responsive center-block' src='"+data+"' alt='' />" + '<input type="hidden" class="'+row.id+'">';
                        }
                    },
                    {"width": "15%","data": "name"},
                    {
                        "width": "20%",
                        "data": "address",
                        "render": function(data, type, row, meta) {
                            return row.province + row.city + row.district + row.address;
                        }
                    },
                ],
                "language": {
                    url: '/public/static/assets/pages/Chinese.json'
                },
                "pageLength": 5,
                "columnDefs": [{
                    "orderable": false,
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){   //将每张图片放到相应预览位置
                    var $displayType = $('.iconAreaList').find("input[name='displayType"+index+"']:checked").val();

                    var $item = '<div class="article_small relative">';
                    $item += '<div class="con relative">';
                        $item += '<h5>'+aData['name']+'</h5>';
                        $item += '<p>'+ aData['province'] + aData['city'] + aData['district'] + aData['address'] +'</p>';
                    $item += '</div>';
                    $item += '<img class="img-responsive carousel-inner" src="'+aData['imgUrl']+'" />';
                    $item += '</div>';

                    $(test).find('.col-md-12 .nearbystore').append($item);
                },
                "fnInitComplete": function() {}
            });
        });
    };

    // 分割线
    var handle_dividingline = function () {
        //
    };

    // 新增模块数据提交
    var ajaxReq = function (param) {
        $.ajax({
            url : wxFrameConf_url,
            type : 'PUT',
            dataType : 'json',
            contentType:"application/json; charset=utf-8",
            data : JSON.stringify(param),
        }).done(function(data) {
            if (data.code === '1') {
                window.location.reload();
            } else if (data.code === '2') {
                layer.msg(data.message)
            }
        });
    };

    // 新增模块数据提交
    var ajaxFrameReq = function (param, msgId) {
        $.ajax({
            url : wxFrameConf_url,
            type : 'POST',
            dataType : 'json',
            contentType:"application/json; charset=utf-8",
            data : JSON.stringify(param),
        }).done(function(data) {
            if (data.code === '1') {    // 正确
                window.location.reload();
            } else if (data.code === '2') {// 错误
                msgId.prev().attr('disabled',false);
                msgId.html(data.message);
            }
        });
    };

    // 视频模块数据提交
    var ajaxFrameReqVideo = function (param, msgId) {
        $.ajax({
            url : FrameReqVideo_url,
            type : 'POST',
            dataType : 'json',
            contentType:"application/json; charset=utf-8",
            data : JSON.stringify(param),
        }).done(function(data) {
            if (data.code === '1') { // 正确
                window.location.reload();
            } else if (data.code === '2') { // 错误
                msgId.prev().attr('disabled',false);
                msgId.html(data.message);
            }
        });
    };

    // 模块内部 列表的删除
    var deleteComponent = function (_id, table) {
        url = componentDel_url;
        param = {'id':_id};
        var confirmBtn = $(this).data('confirmbtn') ? $(this).data('confirmbtn') : '确定';
        var cancelBtn = $(this).data('cancelbtn') ? $(this).data('cancelbtn') : '取消';
        layer.confirm(
            '确定要删除吗？', // 内容
            {
                // icon: 7,
                title: '删除',// 标题
                btn: [confirmBtn, cancelBtn]  // 按钮
            },
            function(index){
                $.ajax({
                    url : componentDel_url,
                    type : 'delete',
                    dataType : 'json',
                    contentType:"application/json; charset=utf-8",
                    data : JSON.stringify(param),
                    async: false
                }).done(function(data) {
                    if (data.code === '1') {
                        layer.msg('删除成功');
                        table.DataTable().ajax.reload();
                        //table.DataTable().draw(false);
                    } else if (data.code === '2') {
                        layer.msg(data.message);
                    }
                });
                layer.close(index);
            }
        );
    };


    return {
        init: function() {
            _init();

            this.onEvent();
        },

        onEvent: function () {

            // 删除模块
            $("#applet").on('click','.btn_del_module',function(){
                var frameId=$(this).prev().prev().val();
                if(!frameId){
                    frameId=$(this).prev().val();
                }
                if(!frameId){
                    frameId=$(this).prev().prev().prev().val();
                }
                var item = $(this);
                //console.log("删除"+frameId);
                var param={"frameId":frameId};
                url=wxFrameConfDel_url;
                var confirmBtn = $(this).data('confirmbtn') ? $(this).data('confirmbtn') : '确定';
                var cancelBtn = $(this).data('cancelbtn') ? $(this).data('cancelbtn') : '取消';
                layer.confirm(
                    '确定要删除吗？', // 内容
                    {
                        // icon: 7,
                        title: '删除',// 标题
                        btn: [confirmBtn, cancelBtn]  // 按钮
                    },
                    function(index){
                        $.ajax({
                            url : wxFrameConfDel_url,
                            type : 'delete',
                            dataType : 'json',
                            contentType:"application/json; charset=utf-8",
                            data : JSON.stringify(param),
                            async: false
                        }).done(function(data) {
                            if (data.code === '1') {
                                layer.msg('删除成功');
                                item.parent().parent().remove();
                                window.location.reload();
                            } else if (data.code === '2') {
                                layer.msg(data.message);
                            }
                        });
                        layer.close(index);
                    }
                );
            });

            // 关闭弹框
            $(".modal").on('hidden.bs.modal', function(e) {
                $('.modal .alert').css('display', 'none'); // 隐藏提示头
                $('.modal .form-group').removeClass('has-error'); //清除错误信息
                $('.modal input[type="text"]').val(''); // 清空 input
                $('.modal input[type="checkbox"]').prop('checked', false); // 清空 input
            });

            // 模块内部 取消按钮 （通用）
            $("#applet").on('click','.btn_cancle_role',function(){
                $(this).parents("table").find(".btn_edit_role").attr("disabled",false);
                $(this).parents(".site").find(".btn_add_class").attr("disabled",false);
                $(this).parent().parent().remove();
                return false;
            });

            // 添加轮播图
            $(".btn-add-ban").click(function(){
                $('#applet').prepend(advertisement);
                var param={"name":"轮播广告","type":"1","displayType":"1","storeId":storeId,"orderNo":1};
                ajaxReq(param);
            });
            // 添加按钮导航
            $(".btn-add-nav").click(function(){
                $('#applet').prepend(iconArea);
                var param={"name":"图标按钮","type":"2","displayType":"3","storeId":storeId,"orderNo":1};
                ajaxReq(param);
            });
            // 添加推荐内容
            $(".btn-add-pro").click(function(){
                $('#applet').prepend(commodity);
                var param={"name":"推荐内容","type":"10","displayType":"1","titleType":"文字标题","storeId":storeId,"orderNo":1};
                ajaxReq(param);
            });
            // 添加自适应图片
            $(".btn-add-pic").click(function(){
                $('#applet').prepend(pic);
                var param={"name":"自适应图片","type":"8","displayType":"1","titleType":"文字标题","storeId":storeId,"orderNo":1};
                ajaxReq(param)
            });
            // 添加代金券
            $(".btn-add-quan").click(function(){
                $('#applet').prepend(quan);
                var param={"name":"代金券","type":"9","displayType":"1","titleType":"文字标题","storeId":storeId,"orderNo":1};
                ajaxReq(param)
            });
            // 添加视频
            $(".btn-add-video").click(function() {
                $('#applet').prepend(video);
                var param={"name":"视频","type":"5","displayType":"1","titleType":"文字标题","storeId":storeId,"orderNo":1};
                ajaxReq(param);
            });
            // 添加附近门店
            $(".btn-add-nearbystore").click(function() {
                if($('#applet').find('.nearbystore').length > 0){
                    layer.msg('附近门店只能添加一个！');
                    return false;
                }
                $('#applet').prepend(nearbystore);
                var param={"name":"附近门店","type":"11","displayType":"1","titleType":"文字标题","storeId":storeId,"orderNo":1};
                ajaxReq(param);
            });
            // 添加分割线
            $(".btn-add-dividingline").click(function() {
                $('#applet').prepend(dividingline);
                var param={"name":"分割线","type":"4","displayType":"1","titleType":"文字标题","storeId":storeId,"orderNo":1};
                ajaxReq(param);
            });
        }
    };
}();


// 页面加载完毕 发起请求获取七牛token，通过前台传到七牛
function getTokenMessageForImg(pic_table) {
    if($('#localUp').length <= 0){
        return;
    }
    var url="";
    var qiniupercent="";
    var uploader="already";
    var pickfiles="localUp";
    $.ajax({
        url: token_url,
        type: 'POST',
        data: {},
        cache: false,
        contentType: false,    //不可缺
        processData: false,    //不可缺
        dataType : 'json',
        success: function (data) {
            var obj = data;
            uploaderReadyForImg(obj.uptoken,url,qiniupercent,uploader,pickfiles,pic_table);
        }
    });
}
function uploaderReadyForImg(token,url,qiniupercent,uploader,pickfiles,pic_table){
    var uploaderForImg = Qiniu.uploader({
        runtimes: 'html5,flash,html4',
        browse_button: pickfiles,     //上传按钮的ID
        // container: uploader,      //上传按钮的上级元素ID
        // drop_element: uploader,
        max_file_size: '500kb',         //最大文件限制
        flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
        dragdrop: false,
        chunk_size: '4mb',              //分块大小
        //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
        uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
        // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
        domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
        multi_selection: false,         //是否允许同时选择多文件
        filters: {
            mime_types: [               //文件类型过滤，这里限制为图片类型
                {title: "Image files", extensions: "jpg,jpeg,gif,png"}
            ]
        },
        auto_start: true,
        unique_names :true,             //自动生成文件名,如果值为false则保留原文件名上传
        init: {
            'FilesAdded': function (up, files) {
                var lw = 0;
                var lh = 0;
                switch(size) {
                    case '1': {
                        lw = 750;
                        lh = 400;
                        break;
                    }
                    case '2': {
                        lw = 690;
                        lh = 370;
                        break;
                    }
                    case '3': {
                        lw = 50;
                        lh = 50;
                        break;
                    }
                }
                plupload.each(files, function(file) {
                    // 文件添加进队列后，处理相关的事情
                    var nativeFile = file.getNative();
                    var img = new Image();
                    img.src = URL.createObjectURL(nativeFile);
                    img.onload = function() {
                        var width = img.naturalWidth;
                        var height = img.naturalHeight;
                        if(width < lw || height < lh) {
                            layer.msg('图片分辨率不足'+lw+'*'+lh+'，图片显示会压缩，请重新上传');
                            up.removeFile(file);
                            return;
                        } else {
                        }
                    }
                });
            },
            'BeforeUpload': function (up, file) {
                // 每个文件上传前，处理相关的事情
            },
            'UploadProgress': function (up, file) {
                //文件上传时，处理相关的事情
                /*可能是文件大小
                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                */
                //上传进度 class="layui-btn" type="button"
                // $('#'+qiniupercent).attr('style','width:'+file.percent+'%');
                // $("#"+qiniupercent).css("background-color","green");

                //console.log(file.percent + "%");
            },
            'UploadComplete': function () {
                //do something
            },
            'FileUploaded': function (up, file, info) {
                //每个文件上传成功后,处理相关的事情,并记录到数据库
                //其中 info 是文件上传成功后，服务端返回的json，形式如
                //{
                //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                //  "key": "gogopher.jpg"
                //}

                var lw = 0;
                var lh = 0;
                switch(size) {
                    case '1': {
                        lw = 750;
                        lh = 400;
                        break;
                    }
                    case '2': {
                        lw = 690;
                        lh = 370;
                        break;
                    }
                    case '3': {
                        lw = 50;
                        lh = 50;
                        break;
                    }
                }

                var domain = up.getOption('domain');
                var res = eval('(' + info.response + ')');
                if(lh == 0 || lw == 0) {
                    var sourceLink = domain + res.key;//获取上传文件的链接地址
                } else {
                    var sourceLink = Qiniu.imageView2({
                        mode: 1,       // 缩略模式，裁剪
                        w: lw,
                        h: lh,
                    },res.key,domain);
                }

                // $("#"+pickfiles).parents(".modal").modal('hide');
                $.ajax({
                    url: record_url,
                    type: 'POST',
                    data: {
                        'imgUrl' : sourceLink,
                        'controller' : 'wxindex'
                    },
                    cache: false,
                    dataType : 'json',
                    success: function (data) {
                        if(data.code === '1') {
                            pic_table.DataTable().ajax.reload();
                            //pic_table.DataTable().draw(false);
                            // pic_table.on('click', '.btn_select_role', function(event) {
                            //     var oData_arr = pic_table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
                            //     var imgUrl = oData_arr[0]['imgUrl'];
                            //     $(e).find('img').attr('src',imgUrl);
                            //     $(this).parents(".modal").modal('hide');
                            // });
                        }
                    }
                });

            },
            'Error': function (up, err, errTip) {
                alert(errTip);
            },
        }
    });
    // uploaderForImg.start();
}
function getVideoTokenMessage(pickfiles) {
    var qiniupercent="";
    $.ajax({
        url: token_url,
        type: 'POST',
        data: {},
        cache: false,
        contentType: false,    //不可缺
        processData: false,    //不可缺
        dataType : 'json',
        success: function (data) {
            var obj = data;
            mdTool.uploaderVideoReady(obj.uptoken,qiniupercent,pickfiles);
        }
    });
}


var pic_table = $('#pic_table');
pic_table.dataTable({
    "processing": true,
    // 开启服务器模式
    serverSide: true,
    destroy:true, //Cannot reinitialise DataTable,解决重新加载表格内容问题
    "ajax": {
        url:layer_img,
    },
    "autoWidth": false,
    "columns": [
        {
            "width": "10%",
            "data": "imgUrl",
            "render": function(data, type, row, meta) {
                return "<img class='btn_select_role' class='img-responsive center-block' src='"+data+"' alt='' />"
            }
        },
    ],
    "language": {
        url: '/public/static/assets/pages/Chinese.json'
    },
    "pageLength": 24,
    "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
    "<t>" +
    "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
    "fnInitComplete": function() {}
});
getTokenMessageForImg(pic_table);


var size = '0';
// 展示图片弹框,图片控件
function getAllPic(e,y) {
    size = y;
    $(".modal").modal("hide");

    var lw = 0;
    var lh = 0;
    switch(size) {
        case '1': {
            lw = 750;
            lh = 400;
            break;
        }
        case '2': {
            lw = 690;
            lh = 370;
            break;
        }
        case '3': {
            lw = 50;
            lh = 50;
            break;
        }
    }

    // 选择图片-单选
    pic_table.on('click', '.btn_select_role', function(event) {
        var oData_arr = pic_table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
        var imgUrl = oData_arr[0]['imgUrl'];
        var img = new Image();
        img.src = imgUrl;
        if(img.width < lw || img.height < lh) {
            layer.msg('图片尺寸不合理，请重新选择');
            return;
        } else {
            $(e).find('img').attr('src',imgUrl);
            $(this).parents(".modal").modal('hide');
        }
    });

    $(".ban-picture").modal("show");
}


/*--------拖动排序--begin-------*/
var arr = '';
var sort = $(".sortable").sortable({
    handle: ".glyphicon-move",
    opacity: 0.7,
    delay: 150,
    cursor: 'move',
    revert: true,
    stop: function() {
        var arr = $(".sortable").sortable('toArray'); //记录sort后的id顺序数组
        var param=new Array(arr.length);
        for(var i=0;i<arr.length;i++){
            var did= arr[i];
            var frameId=$('#'+did+" input[name='frameId']" ).val();
            param[i]={"id":frameId,"orderNo":i+1};
        }
        $.ajax({
            url : move_url,
            type : 'POST',
            dataType : 'json',
            contentType:"application/json; charset=utf-8",
            data : JSON.stringify(param),
        }).done(function(data) {
            if (data.code === '1') { // 正确
                window.location.reload();
            } else if (data.code === '2') { // 错误
                // mdTool.showMessageForHelpBlock(data.message);
            }
        });
        //拖拽后利用localStorage记录顺序
        localStorage.arr = arr;
    }
});
var localSt = localStorage.arr;
/*--------拖动排序--end----------*/



$(function() {
    Wxindex.init();

    if($('.btn-video-site').length >= 1) {  //存在视频模块
        $('.btn-video-site').each(function(i){
            var listid = $(this).attr('id');
            var index = listid.substr(4);
            getVideoTokenMessage("videofiles"+index);

        });
    }
    $(".banner .item:first-child").addClass("active");

    $('.square').colpick({
        colorScheme:'dark',
        layout:'rgbhex',
        color:'ffffff',
        livePreview:0,
        onSubmit:function(hsb,hex,rgb,el) {
            $(el).css('background-color', '#'+hex);
            $(el).colpickHide();
        }
    });


    $(".stylelist ul li:first-child input[type='radio']").attr("checked","checked");
    $(".styleCon .pic_con").eq(0).show();
    $(".stylelist ul li").click(function(){
        var n = $(this).index();
        $(".styleCon .pic_con").eq(n).show().siblings().hide();
    });

    var $divWidth = $('#iconArea img').width();
    $('#iconArea img').css({'height':$divWidth});
});
